package org.apache.ibatis.usage;

import org.apache.ibatis.domain.blog.Blog;
import org.apache.ibatis.domain.blog.mappers.BlogMapper;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.jupiter.api.Test;

import javax.sql.DataSource;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.ReentrantLock;

/**
 * sample usage from official document.
 */
public class WithoutXml {
  @Test
  public void buildWithoutXml() {
    DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
    //处理事务
    TransactionFactory transactionFactory = new JdbcTransactionFactory();
    //环境
    Environment environment = new Environment("development", transactionFactory, dataSource);
    Configuration configuration = new Configuration(environment);
    configuration.addMapper(BlogMapper.class);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
    try (SqlSession session = sqlSessionFactory.openSession()) {
      //这里的org.mybatis.example.BlogMapper.selectBlog是*mapper.xml文件中的id
      Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
    }
  }
  public void assistReadSourceCode(){
    ReentrantLock lock=new ReentrantLock();
    AbstractQueuedSynchronizer queuedSynchronizer=new AbstractQueuedSynchronizer() {
      @Override
      protected boolean tryAcquire(int arg) {
        return super.tryAcquire(arg);
      }

      @Override
      protected boolean tryRelease(int arg) {
        return super.tryRelease(arg);
      }

      @Override
      protected int tryAcquireShared(int arg) {
        return super.tryAcquireShared(arg);
      }

      @Override
      protected boolean tryReleaseShared(int arg) {
        return super.tryReleaseShared(arg);
      }

      @Override
      protected boolean isHeldExclusively() {
        return super.isHeldExclusively();
      }

      @Override
      public String toString() {
        return super.toString();
      }
    };
  }
  private static class BlogDataSourceFactory {
    public static DataSource getBlogDataSource() {
      return null;
    }
  }
}
